using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.Entity.DomainModels;
using SqlSugar;
using VOL.Core.BaseProvider;

namespace VOL.demo.Repositories
{
    public partial class StockInOrderModelRepository
    {
        /// <summary>
        /// 分页查询入库单（带关联查询和计算字段）
        /// </summary>
        public async Task<(List<StockInOrderModel> Data, int TotalCount)> GetStockInOrderPageListAsync(
            int pageIndex, 
            int pageSize, 
            string stockInCode = null, 
            int? status = null, 
            long? warehouseId = null, 
            DateTime? stockInDate = null,
            long? inOutTypeId = null)
        {
            // 先查询主表数据
            var query = DbContext.Queryable<StockInOrderModel>()
                .LeftJoin<warehousemodel>((sio, w) => sio.warehouseId == w.Id)
                .LeftJoin<suppliermodel>((sio, w, s) => sio.supplierId == s.Id)
                .LeftJoin<Sys_User>((sio, w, s, u) => sio.userId == u.User_Id)
                .Where((sio, w, s, u) => sio.IsDel == 0)
                .WhereIF(!string.IsNullOrEmpty(stockInCode), (sio, w, s, u) => sio.stockInCode.Contains(stockInCode))
                .WhereIF(status.HasValue, (sio, w, s, u) => sio.status == status)
                .WhereIF(warehouseId.HasValue, (sio, w, s, u) => sio.warehouseId == warehouseId)
                .WhereIF(stockInDate.HasValue, (sio, w, s, u) => sio.stockInDate.Value.Date == stockInDate.Value.Date)
                .WhereIF(inOutTypeId.HasValue, (sio, w, s, u) => sio.inOutTypeId == inOutTypeId)
                .Select((sio, w, s, u) => new StockInOrderModel
                {
                    Id = sio.Id,
                    stockInCode = sio.stockInCode,
                    inOutTypeId = sio.inOutTypeId,
                    warehouseId = sio.warehouseId,
                    stockInDate = sio.stockInDate,
                    relatedOrderCode = sio.relatedOrderCode,
                    supplierId = sio.supplierId,
                    contactPerson = sio.contactPerson,
                    contactPhone = sio.contactPhone,
                    userId = sio.userId,
                    remark = sio.remark,
                    status = sio.status,
                    auditUser = sio.auditUser,
                    auditTime = sio.auditTime,
                    Creator = sio.Creator,
                    CreateDate = sio.CreateDate,
                    Modifier = sio.Modifier,
                    ModifyDate = sio.ModifyDate,
                    CreateID = sio.CreateID,
                    ModifyID = sio.ModifyID,
                    WarehouseName = w.WarehouseName,
                    SupplierName = s.SupplierName,
                    UserName = u.UserTrueName,
                    DeptName = "",  // 入库单没有部门字段，设为空字符串
                    StatusName = sio.status == 1 ? "草稿" :
                                sio.status == 2 ? "待审核" :
                                sio.status == 3 ? "驳回" :
                                sio.status == 4 ? "已完成" : "未知"
                })
                .OrderByDescending(sio => sio.CreateDate);

            var totalCount = await query.CountAsync();
            var data = await query.ToPageListAsync(pageIndex, pageSize);

            // 为每个入库单计算汇总数据
            foreach (var item in data)
            {
                try
                {
                    // 获取明细数据并计算汇总
                    var details = await DbContext.Queryable<StockInOrderItemModel>()
                        .Where(soi => soi.StockInCode == item.stockInCode && soi.IsDel == 0)
                        .ToListAsync();

                    // 计算总数量和总金额（支持分批入库）
                    item.TotalQuantity = details.Sum(d => d.thisTimeQuantity ?? 0);
                    
                    // 计算总金额：upprice 是 varchar 类型，需要转换为 decimal
                    item.TotalAmount = details.Sum(d => 
                    {
                        if (!string.IsNullOrEmpty(d.upprice) && decimal.TryParse(d.upprice, out decimal price))
                        {
                            return price;
                        }
                        return 0;
                    });
                    
                    // 处理入库货品字段，限制显示长度
                    var goods = details.Select(d => d.GoodsName).Where(g => !string.IsNullOrEmpty(g)).Distinct().ToList();
                    
                    if (goods.Count > 3)
                    {
                        item.StockInGoods = string.Join("、", goods.Take(3)) + $"等{goods.Count}项.......";
                    }
                    else
                    {
                        item.StockInGoods = string.Join("、", goods);
                    }
                }
                catch (Exception ex)
                {
                    // 如果明细表查询失败，设置默认值
                    item.TotalQuantity = 0;
                    item.TotalAmount = 0;
                    item.StockInGoods = "明细数据查询失败";
                }
            }

            return (data, totalCount);
        }
    }
}

